import { useState } from "react";
import { loginAPI } from "../api/login";
import { Button, Checkbox, Form, Input } from "antd";
import { message } from "antd";
import { setToken } from "../utils/tools";
import "../styles/LoginStyle.scss";
//实现编程时跳转
import { useNavigate } from "react-router-dom";
import { useAppDispatch } from "../store/hooks";
import { settoken } from "../store/counter/showSlice";
function Login() {
  const navigate = useNavigate();
  type valu = {
    username: string;
    password: string;
  };
  const dispatch = useAppDispatch();
  const onFinish = async (val: valu) => {
    console.log("Success:", val);
    const res = await loginAPI({
      userName: val.username,
      password: val.password,
    });
    console.log(res.data);
    //验证输入框的值，返回错误信息！
    if (res.data.code === 1) {
      message.success("登录成功!");
      // eslint-disable-next-line react-hooks/rules-of-hooks

      //存入token
      setToken(res.data.data);
      dispatch(settoken(res.data.data));
      //存入用户名
      localStorage.setItem("uname", val.username);
      //跳转到后台管理界面
      console.log(11);
      navigate("/home");
    } else if (res.data.code === 0) {
      //message.error 是antd中用来提示错误信息的。
      message.error(res.data.data);
    }
  };
  const [check, setCheck] = useState(true);
  console.log(check);
  return (
    <div className="login">
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        style={{ maxWidth: 600 }}
        initialValues={
          check
            ? {
                // 表单自动填充的字段
                username: "admin",
                password: "admin",
              }
            : { username: "", password: "" }
        }
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox
            checked={check}
            //选择变化的回调，配合表单的属性initialValues（自动填充字段）实现自动填充密码和用户名console.log(e.target.checked)true/false
            onChange={(e) => setCheck(e.target.checked)}
          >
            请记住我的选择！
          </Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
